package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.inter.mapper.*;
import com.ruoyi.system.V2.inter.service.IInterRecService;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.service.IOutApi;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaJymItemExternalGoodsBatchtaskQueryRequest;
import com.taobao.api.response.AlibabaJymItemExternalGoodsBatchtaskQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
@Slf4j
public class JYMTask {

    @Resource
    private InterRecMapper interRecMapper;
    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private TimeUpMapper timeUpMapper;
    @Resource
    private SalePartnerMapper salePartnerMapper;
    @Resource
    private IInterRecService interRecService;
    @Autowired
    private IOutApi iOutApi;

    @Resource
    private JymtaskMapper jymtaskMapper;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void jymAddStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setAddStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"add");
            }
        }
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void jymEditStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

//        SalePartner salePartner = salePartnerMapper.selectSalePartnerSaleCode("JYM");
        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setEditStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"edit");
            }
        }
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void jymDelStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

//        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(congig);

        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setDelStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            try {
                Thread.sleep(1000l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"del");
            }
        }
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void jym2AddStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

//        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(congig);

        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM2");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setAddStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"add");
            }
        }
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void jym2EditStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

//        SalePartner salePartner = salePartnerMapper.selectSalePartnerSaleCode("JYM");
        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM2");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setEditStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"edit");
            }
        }
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void jym2DelStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

//        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(congig);

        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM2");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setDelStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"del");
            }
        }
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void jym3AddStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

//        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(congig);

        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM3");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setAddStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"add");
            }
        }
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void jym3EditStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

//        SalePartner salePartner = salePartnerMapper.selectSalePartnerSaleCode("JYM");
        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM3");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setEditStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"edit");
            }
        }
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void jym3DelStatusRef() {
        /**
         * 1、查询所有交易猫的数据
         * 2、查询成功已添加的
         * 3、结果通知
         */

//        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(congig);

        SalePartner salePartner = new SalePartner();
        salePartner.setSaleName("JYM3");
        List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerList(salePartner);
        for (SalePartner partner : salePartnerList) {
            Jymtask jymtask = new Jymtask();
            jymtask.setDelStatus("0");
            jymtask.setSalecode(partner.getSaleName());
            List<Jymtask> jymtasks = jymtaskMapper.selectJymtaskList(jymtask);

            for (Jymtask task : jymtasks) {
                selectJYMData(task,partner,"del");
            }
        }
    }

    @Resource
    private ArtRecMapper artRecMapper;

    private void selectJYMData(Jymtask jymtask,SalePartner salePartner,String type){

        TaobaoClient client = new DefaultTaobaoClient(OutUrlConstant.JYMURL, salePartner.getSaleKey(), salePartner.getOther());

        log.info("accountId={}",jymtask.getAccountid());
        Date updateTime = jymtask.getCreateTime();
        AlibabaJymItemExternalGoodsBatchtaskQueryRequest req = new AlibabaJymItemExternalGoodsBatchtaskQueryRequest();
        AlibabaJymItemExternalGoodsBatchtaskQueryRequest.GoodsBatchTaskQueryDto obj1 = new AlibabaJymItemExternalGoodsBatchtaskQueryRequest.GoodsBatchTaskQueryDto();
        if (Objects.equals(LCConstant.interAdd,type) && Objects.nonNull(jymtask.getJymAddTaskId())){
            obj1.setBatchId(jymtask.getJymAddTaskId());
        }
        if (Objects.equals(LCConstant.interEdit,type) && Objects.nonNull(jymtask.getJymEditTaskId())){
            obj1.setBatchId(jymtask.getJymEditTaskId());
        }
        if (Objects.equals(LCConstant.interDel,type) && Objects.nonNull(jymtask.getJymDelTaskId())){
            obj1.setBatchId(jymtask.getJymDelTaskId());
        }

        req.setGoodsBatchTaskQuery(obj1);
        AlibabaJymItemExternalGoodsBatchtaskQueryResponse rsp = null;
        try {
            rsp = client.execute(req);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        log.info("响应参数={}",JSONObject.toJSONString(req));
        log.info("请求参数={}",rsp.getBody());
        JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
        jsonObject = jsonObject.getJSONObject("alibaba_jym_item_external_goods_batchtask_query_response");
        Boolean succeed = jsonObject.getBoolean("succeed");
        if (succeed) {
            String result = jsonObject.getString("result");

            String listStr = JSONObject.parseObject(result).getString("goods_batch_sub_task_list");
            String taskList = JSONObject.parseObject(listStr).getString("goods_batch_sub_task");
            JSONArray array = JSONObject.parseArray(taskList);
            if (!CollectionUtils.isEmpty(array)) {
                Object o = array.get(0);
                String task = JSONObject.toJSONString(o);
                JSONObject taskJson = JSONObject.parseObject(task);
                String status = taskJson.getString("status");
                Date nowDate = DateUtils.getNowDate();
                long diff = (nowDate.getTime() - updateTime.getTime()) / 1000 / 60;
                if (diff > 3){
                    if (!Objects.equals(status, "1")){
                        if (!Objects.equals(status, "3") && !Objects.equals(status, "2") ) {

//                            interRecMapper.deleteInterAccount(jymtask.getAccountid().toString(),salePartner.getSaleName());
//                            artRecMapper.deleteArtRecCode(jymtask.getAccountid(),salePartner.getId());
                            jymtask.setRes(result);
                            if (Objects.equals(LCConstant.interAdd,type)){
                                jymtask.setAddStatus("1");
                            }
                            if (Objects.equals(LCConstant.interEdit,type)){
                                jymtask.setEditStatus("1");
                            }
                            if (Objects.equals(LCConstant.interDel,type)){
                                jymtask.setDelStatus("1");
                            }
                            jymtaskMapper.updateJymtask(jymtask);
                        }else{
                            log.info("taskJson={}",taskJson);
                            String external_goods_id = taskJson.getString("external_goods_id");
                            String goods_id = taskJson.getString("goods_id");
//                                GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(jymtask.getAccountid());

//                                    Integer saleState = goodsInfo.getSaleState();
//                                    if (!Objects.equals(saleState,SalerStatus.unsold.getCode())){
//                                        //如果状态不对，调取下架接口
//                                        iOutApi.del(goodsInfo.getId(),salePartner.getId(),1,null);
//                                    }
                            jymtask.setRes(result);
                            jymtask.setJymId(Long.parseLong(goods_id));
                            if (Objects.equals(LCConstant.interAdd,type)){

                                jymtask.setAddStatus("1");
                                ArtRec artRec = new ArtRec();
                                artRec.setAccountId(jymtask.getAccountid());
                                artRec.setCreateId(jymtask.getCreateId());
                                artRec.setConfig(salePartner.getId());
                                artRec.setSaleCode(salePartner.getSaleName());
                                artRec.setType(type);
                                artRec.setOutid(goods_id);
                                artRec.setCreateTime(new Date());

                                ArtRec artRecSelect = new ArtRec();
                                artRecSelect.setConfig(salePartner.getId());
                                artRecSelect.setAccountId(jymtask.getAccountid());

                                artRecMapper.deleteArtRecCode(jymtask.getAccountid(), salePartner.getId());
//                                artRecMapper.insertArtRec(artRec);

                                List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRec);
                                if (CollectionUtils.isEmpty(artRecs)) {
                                    artRecMapper.insertArtRec(artRec);
                                } else {
                                    Long id = artRecs.get(0).getId();
                                    artRec.setId(id);
                                    artRecMapper.updateArtRec(artRec);
                                }

                            }
                            if (Objects.equals(LCConstant.interEdit,type)){
                                jymtask.setEditStatus("1");
                            }
                            if (Objects.equals(LCConstant.interDel,type)){
                                jymtask.setDelStatus("1");
                            }
                            jymtaskMapper.updateJymtask(jymtask);
                        }
//                        else {
//                                    jymtask.setRes("因数据原因未查询到账号 返回结果：" + result);
//                                    if (Objects.equals(LCConstant.interAdd,type)){
//                                        jymtask.setAddStatus("1");
//                                    }
//                                    if (Objects.equals(LCConstant.interEdit,type)){
//                                        jymtask.setEditStatus("1");
//                                    }
//                                    if (Objects.equals(LCConstant.interDel,type)){
//                                        jymtask.setDelStatus("1");
//                                    }
//                                    jymtaskMapper.updateJymtask(jymtask);
//                                }
                    }
                }
            }
        }
    }


    /**
     * 盼之接口刷新
     */
    public void refPZZ(String name,String pwd){

        JSONObject req = new JSONObject();
        req.put("pageSize",10);
        JSONObject action = new JSONObject();
        action.put("status","ON_STAND");
        req.put("action",action);
        String url = "https://www.pzds.com/api/v2/userCenter/pageGoods";

        String token = "";
        JSONObject reqtoken = new JSONObject();
        JSONObject actiontoken = new JSONObject();
        actiontoken.put("phone",name);
        String sign = DigestUtils.md5Hex(pwd);
        actiontoken.put("password",sign);
        reqtoken.put("action",actiontoken);

        Map<String,String> head = new HashMap<>();
        head.put("content-type","application/json");

        String tokenUrl = "https://www.pzds.com/api/v2/user/public/login/password";
        try {
            String tokenres = HttpUtils.sendPost(tokenUrl, JSONObject.toJSONString(reqtoken), head);
            JSONObject jsonObject = JSONObject.parseObject(tokenres);
            token = jsonObject.getString("data");
        } catch (IOException e) {
            e.printStackTrace();
        }
        head.put("token",token);

        Integer page = 0;
        boolean flag = true;
        while (flag){
            page++;
            req.put("page",page);
            String res = "";
            try {
                res = HttpUtils.sendPost(url, JSONObject.toJSONString(req), head);
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject jsonObject = JSONObject.parseObject(res);
            JSONObject data = jsonObject.getJSONObject("data");
            Integer totalPages = data.getInteger("totalPages");
            if (page == totalPages){
                flag = false;
            }
            if (totalPages > 0){
                String records = data.getString("records");
                List<JSONObject> jsonObjects = JSONObject.parseArray(records, JSONObject.class);
                if (jsonObjects.size() < 10){
                    flag = false;
                }
                for (JSONObject object : jsonObjects) {
                    String goodsNo = object.getString("goodsNo");
                    try {

                        String detailsUrl = "https://www.pzds.com/api/v2/userCenter/addGoodsTempHeat";
                        JSONObject detailsQeq = new JSONObject();
                        JSONObject actionDetails = new JSONObject();
                        actionDetails.put("goodsNo",goodsNo);
                        detailsQeq.put("action",actionDetails);
                        String  detaisStr = HttpUtils.sendPost(detailsUrl, JSONObject.toJSONString(detailsQeq), head);
                        System.out.println(detaisStr);
                        Thread.sleep(2000l);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void timeUpOnAccount(){
        TimeUp timeUp = new TimeUp();
        List<TimeUp> timeUps = timeUpMapper.selectTimeUpList(timeUp);
        for (TimeUp up : timeUps) {
            timeUpOn(up.getUserId(),up.getConfig());
            try {
                Thread.sleep(2000l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //标签同步
    public void timeUpOn(Long createId,Long config) {

        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setSaleState(1);
        goodsInfo.setCreateId(createId);
        List<GoodsInfo> goodsInfoList = goodsInfoMapper.selectGoodsInfoList(goodsInfo);

        Set<Integer> ids = rodomImter(goodsInfoList.size());

        for (Integer index : ids) {
            //开始下架
            GoodsInfo info = goodsInfoList.get(index);
            exitdelTask(info.getId(),config);
        }

        try {
            Thread.sleep(5000l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (Integer index : ids) {
            //开始下架
            GoodsInfo info = goodsInfoList.get(index);
            exitAddTask(info.getId(),config);
        }
    }

    public Set<Integer> rodomImter(Integer maxNum) {

        Set<Integer> result = new HashSet<>();

        Random ran = new Random();
        Set <Integer> set = new HashSet<Integer>();
        while(set.size()==10?false:true){
            int num = ran.nextInt(maxNum)+1;
            set.add(num);
        }
        Iterator<Integer> it = set.iterator();
        int count = 0;
        while(it.hasNext()){
            System.out.println("第"+ ++count +"个随机数 =="+it.next());
            result.add(it.next());
        }

        return result;
    }

    @Async
    public void exitdelTask(Long id,Long config){
        iOutApi.del(id,config,0,null);
    }
    @Async
    public void exitAddTask(Long id,Long config){
        iOutApi.add(id,config);
    }

    @Resource
    private SysDictDataMapper sysDictDataMapper;
    private String getVersion() {
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("JYMVERSION");
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(sysDictDataList)) {
            return sysDictDataList.get(0).getDictValue();
        }
        return "";
    }

}
